package com.fly.monitor.core.helper;

import com.fly.monitor.core.enums.TraceKey;
import org.slf4j.MDC;

import java.util.UUID;

/**
 * @author Mr.Fu
 * @date 2022/11/27 下午3:35
 */
public class MDCHelper {

    /**
     * 初始化并返回traceId
     *
     * @return traceId
     */
    public static String init() {
        String traceId = generateTraceId();
        MDC.put(TraceKey.TRACE_ID.getKey(), traceId);
        MDC.put(TraceKey.SPAN_ID.getKey(), "0");
        MDC.put(TraceKey.LOGIC_ID.getKey(), "0");
        return traceId;
    }

    /**
     * increment logicId
     *
     * @param logicId logicId
     * @return logicIdStr
     */
    public static String incrLogicId(String logicId) {
        return String.valueOf(Integer.parseInt(logicId) + 1);
    }


    /**
     * 从 MDC 中清除当前线程的 Trace信息
     */
    public static void clear() {
        MDC.clear();
    }


    /**
     * 生成traceId
     *
     * @return traceId
     */
    public static String generateTraceId() {
        return UUID.randomUUID().toString().replace("-", "");
    }

    /**
     * 生成新的spanId
     *
     * @param spanId  span id
     * @param logicId logic id
     * @return span id
     */
    public static String getNewSpanId(String spanId, String logicId) {
        return spanId + "." + logicId;
    }
}
